#include "scan.h"

uint8_t SCAN_WaitRply(void)
{
    uint8_t timeout = 200;
    while(!Scanner_Get() && timeout)
    {
        delay_ms(1);
        timeout--;
        if(timeout == 0)    return 1;
    }
    if(uart_msg.scanner.payload[2] == 0x00) return 0;
    else    return 1;
}

uint8_t SCAN_FactoryReset(void)
{
    uint8_t factory_cmd[] = {0x7e, 0x00, 0x09, 0x01, 0x00, 0x00, 0xff, 0xab, 0xcd};
    
    UART_SendArray(SCANNER, factory_cmd, sizeof(factory_cmd));
    return SCAN_WaitRply();
}

uint8_t SCAN_WriteCmd(uint8_t addr, uint8_t data)
{
    uint8_t write_cmd[] = {0x7e, 0x00, 0x08, 0x01, 0x00, addr, data, 0xab, 0xcd};
    
    UART_SendArray(SCANNER, write_cmd, sizeof(write_cmd));
    return SCAN_WaitRply();
}

uint8_t SCAN_ReadCmd(uint8_t addr)
{
    uint8_t read_cmd[] = {0x7e, 0x00, 0x07, 0x01, 0x00, addr, 0x01, 0xab, 0xcd};
    
    UART_SendArray(SCANNER, read_cmd, sizeof(read_cmd));
    if(!SCAN_WaitRply())    return uart_msg.scanner.payload[4]; //返回向扫描器读取到的数据
    else                    return 0xff;
}

uint8_t SCAN_SaveCmd(void)
{
    uint8_t save_cmd[] = {0x7e, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0xab, 0xcd};
    
    UART_SendArray(SCANNER, save_cmd, sizeof(save_cmd));
    return SCAN_WaitRply();
}

//void SCAN_Init(void)
//{
//    uint8_t error = 0;

//    if(SCAN_WriteCmd(SCAN_CMD00_ADDR, SCAN_CMD00))  error++;
//    if(SCAN_WriteCmd(SCAN_CMD0D_ADDR, SCAN_CMD0D))  error++;
//    if(SCAN_WriteCmd(SCAN_CMD60_ADDR, SCAN_CMD60))  error++;
//    if(SCAN_SaveCmd())  error++;
//    
//    if(error)   UART_Printf(SERIAL, "Scanner init failed!");
//}
